package org.example.contestb.util;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Comparator;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class PklFileCopier {

    private static final Path sourceDir = Paths.get("D:\\Python\\pyproject\\pkls_300"); // 源文件夹路径
    private static final Path destDir = Paths.get("E:\\pkl_300"); // 目标文件夹路径
    private static final long initialDelay = 0; // 初始延迟时间（秒）
    private static final long period = 5; // 时间间隔（秒）
    private static List<Path> pklFiles;

    static {
        pklFiles = new ArrayList<>();
        try {
            Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (file.toString().endsWith(".pkl")) {
                        pklFiles.add(file);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
            // 对文件列表进行排序
            pklFiles.sort(Comparator.comparingInt(o -> {
                String fileName = o.getFileName().toString();
                // 假设文件名格式为 "数字.pkl"，例如 "1.pkl", "100.pkl"
                String numberPart = fileName.substring(0, fileName.length() - 4); // 移除 ".pkl"
                return Integer.parseInt(numberPart);
            }));
            System.out.println(pklFiles);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        AtomicInteger i= new AtomicInteger(0);
        Runnable task = () -> {
            try {
                copyNextPklFile(i);
                i.addAndGet(1);
                System.out.println(i.get());
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        };

        scheduler.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
    }

    private static void copyNextPklFile(AtomicInteger i) throws IOException, InterruptedException {
        if (!pklFiles.isEmpty()) {
            Path fileToCopy = pklFiles.get(i.get()); // 获取第一个pkl文件
            Path destPath = destDir.resolve(fileToCopy.getFileName());
            Files.copy(fileToCopy, destPath, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("Copied: " + fileToCopy.getFileName());
            // 如果需要删除已复制的文件，可以取消下一行注释
            // Files.delete(fileToCopy);
        } else {
            System.out.println("No more .pkl files to copy.");
        }
    }
}